import {Component, OnInit, OnDestroy} from '@angular/core';
import {DatePipe} from '@angular/common';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {ActivatedRoute} from '@angular/router';

import {defalutImg} from 'src/app/comm';
import {LoveRecycManageService} from '../love-recyc-manage.service';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, debounceTime, map, switchMap} from 'rxjs/operators';

@Component({
  selector: 'app-love-model-config',
  templateUrl: './love-model-config.component.html',
  styleUrls: ['./love-model-config.component.scss'],
  providers: [DatePipe]
})
export class LoveModelConfigComponent implements OnInit, OnDestroy {

  routerParams: any = {};
  fallback: string = defalutImg;

  // 品牌options
  baradListForm: any = {
    isLoading: false,
    page: 1,
    pageSize: 15,
    total: 0
  };
  brandOptions: any = [];

  // 系列options
  seriesListForm: any = {
    isLoading: false,
    page: 1,
    pageSize: 15,
    total: 0
  };
  seriesOptions: any = [];

  // 机型名称options
  orderCodeOptions: any = [];
  nzFilterOption = (): boolean => true;
  isOrderCodeLoading: boolean = false;
  searchChange$ = new BehaviorSubject('');

  seachParams: any = {
    name: '',
    brandId: '', // 品牌ID
    category: '', // 品牌ID
    seriesId: '', // 系列ID
    beginTime: '',
    endTime: '',
    status: '',
  };
  updateTimes: any = [];

  // Table Data
  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  // Modal
  validateForm!: FormGroup;
  isVisible: boolean = false;
  modalType: number = 0; // 0：新增，1：编辑
  modalItem: any = {};
  subModalLoding: boolean = false;
  uploadLoading: boolean = false;
  modalSeriesOptions: any = []; // 系列下拉list

  // 存储容量 | 颜色
  capacityColorObjs = {
    capacityArr: [],
    colorArrs: []
  };

  constructor(
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private message: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private services: LoveRecycManageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routerParams = res || {};
    });
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      name: ['', [Validators.required]],
      alias: [''],
      brandId: ['', [Validators.required]],
      seriesId: ['', [Validators.required]],
      url: [''],
      status: [0],
      memory: [''],
      color: [''],
    });

    this.getBrandOption();
    this.getSeriesOption();

    if (this.routerParams.brandId) {
      this.seachParams.brandId = Number(this.routerParams.brandId);
    } else if (this.routerParams.seriesId) {
      this.seachParams.seriesId = Number(this.routerParams.seriesId);
    }

    // 机型名称下拉 防抖
    this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .subscribe((value: any) => {
        if (!value && !this.seachParams.brandId && !this.seachParams.seriesId) {
          this.orderCodeOptions = [];
          return;
        }
        this.loadOrderCodeOptions(value);
      });

    this.loadTable();
  }

  ngOnDestroy(): void {
    this.searchChange$.unsubscribe();
  }

  // 获取品牌options
  async getBrandOption() {
    try {
      let params = {
        page: this.baradListForm.page,
        pageSize: 99999
      };
      this.baradListForm.isLoading = true;
      const res: any = await this.services.getRecycleBrandList(params);
      this.baradListForm.isLoading = false;

      if (res.code == 0) {
        const {records, total}: any = res.data || {};
        this.brandOptions = this.brandOptions.concat(records || []);
        this.baradListForm.total = total || 0;
      } else {
        this.message.error(res.message || '品牌列表获取失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 获取seach系列options
  async getSeriesOption() {
    try {
      let params = {
        brandId: this.seachParams.brandId,
        page: this.seriesListForm.page,
        pageSize: this.seriesListForm.pageSize
      };
      this.seriesListForm.isLoading = true;
      const res: any = await this.services.getRecycleSeriesList(params);
      this.seriesListForm.isLoading = false;

      if (res.code == 0) {
        const {records, total}: any = res.data || {};
        this.seriesOptions = this.seriesOptions.concat(records || []);
        this.seriesListForm.total = total || 0;
      } else {
        this.message.error(res.message || '品牌列表获取失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  /**
   * Select Options More
   * @param num 0：品牌，1：系列
   * @returns
   */
  loadMore(num: number) {
    if (num == 0) {
      if (this.baradListForm.total <= this.brandOptions.length) {
        return;
      }
      this.baradListForm.page += 1;
      this.getBrandOption();
    } else if (num == 1) {
      if (this.seriesListForm.total <= this.seriesOptions.length) {
        return;
      }
      this.seriesListForm.page += 1;
      this.getSeriesOption();
    }
  }

  /**
   * 机型名称下拉 options
   * ----------------------------------------------------------------
   */
  async loadOrderCodeOptions(seriesName?: string) {
    let params = {
      brandId: this.seachParams.brandId,
      seriesId: this.seachParams.seriesId,
      name: seriesName || '',
      page: 1,
      pageSize: 1000000
    };
    this.orderCodeOptions = [];
    this.isOrderCodeLoading = true;
    const res: any = await this.services.getRecycleModelList(params);
    this.isOrderCodeLoading = false;

    if (res.code == 0) {
      const {records, total} = res.data || {};
      this.orderCodeOptions = records || [];
    } else {
      this.orderCodeOptions = [];
    }
  }

  orderCodeSearch(value: any) {
    this.searchChange$.next(value);
  }

  // Table Data
  async loadTable() {
    try {
      let params: any = {
        ...this.seachParams,
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      };
      this.tableParams.tableLoading = true;
      const res: any = await this.services.getRecycleModelList(params);
      this.tableParams.tableLoading = false;

      if (res.code == 0) {
        const {records, total} = res.data || {};
        this.tableData = records || [];
        this.tableParams.total = total || 0;
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 品牌change
  seachBrandChange(val: any) {
    this.seachParams.seriesId = '';
    this.seachParams.name = '';
    this.orderCodeOptions = [];

    this.seriesListForm.page = 1;
    this.seriesListForm.total = 0;
    this.seriesOptions = [];
    this.getSeriesOption();

    if (val) {
      this.loadOrderCodeOptions();
    }
  }

  // 系列change
  seriesChange(val: any) {
    this.seachParams.name = '';
    this.orderCodeOptions = [];

    if (val) {
      this.loadOrderCodeOptions();
    }
  }

  seachData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    Object.keys(this.seachParams).forEach((key: any) => {
      this.seachParams[key] = '';
    });
    this.updateTimes = [];

    this.tableParams.page = 1;
    this.loadTable();
  }

  // 更新时间change
  timeChange(result: Date[]) {
    this.seachParams.beginTime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    this.seachParams.endTime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
  }

  // 获取Modal系列list
  async getModalSeriesOptions() {
    try {
      let params = {
        brandId: this.validateForm.value.brandId,
        page: 1,
        pageSize: 99999
      };
      const res: any = await this.services.getRecycleSeriesList(params);
      const {records} = res.data || {};
      this.modalSeriesOptions = records || [];
    } catch (error: any) {
      this.modalSeriesOptions = [];
      this.message.error(error);
    }
  }

  /**
   * 新增、编辑
   * @param num 0：新增，1：编辑
   * @param item
   */
  showModal(num: number, item?: any) {
    this.capacityColorObjs.capacityArr = [];
    this.capacityColorObjs.colorArrs = [];
    if (num == 1) {
      this.modalItem = item;
      this.validateForm.patchValue({
        name: item.name,
        alias: item.alias,
        brandId: item.brandId,
        seriesId: item.seriesId,
        url: item.url,
        memory: item.memory,
        color: item.color,
        status: item.status,
      });
      this.capacityColorObjs.capacityArr = item.memory ? item.memory.split(',') : [];
      this.capacityColorObjs.colorArrs = item.color ? item.color.split(',') : [];
    }

    this.modalType = num;
    this.getModalSeriesOptions();
    this.isVisible = true;
  }

  handleCancel(): void {
    this.isVisible = false;
    this.modalItem = {};
    this.seachParams.brandId = '';
    this.validateForm.reset();
  }

  // 删除
  async changeStatus(id: any, status: number) {
    try {
      const params = {
        id,
        status, // 0-禁用 1-启用 2-删除
      };
      const res: any = await this.services.updateRecycleModelItem(params);
      if (res.code === 0) {
        this.message.success('操作成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '操作失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // Modal 品牌选择
  brandChange(value: any) {
    this.validateForm.get('seriesId')?.setValue('');
    this.getModalSeriesOptions();
  }

  // modal submit
  submitForm(): void {
    if (this.validateForm.valid) {
      this.subFormInterface();
      // this.isVisible = false;
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
    }
  }

  async subFormInterface() {
    try {
      let params: any = {
        ...this.validateForm.value
      };
      let res: any = null;

      this.subModalLoding = true;
      if (this.modalType == 0) {
        res = await this.services.saveRecycleModelItem(params);
      } else {
        params.id = this.modalItem.id;
        res = await this.services.updateRecycleModelItem(params);
      }
      this.subModalLoding = false;

      if (res.code == 0) {
        this.message.success('操作成功');
        this.validateForm.reset();
        this.isVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  /**
   * 容量 | 颜色 change
   * @param value
   * @param str
   */
  tagchange(result: any[], str: string) {
    this.validateForm.get(str)?.setValue(result.join(','));
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 图片上传
  onModalPreview(ev: any) {
    const {originFileObj}: any = ev?.file;
    this.uploadInterface(originFileObj);
  }

  // uploadInterface
  async uploadInterface(file: any) {
    if (!file || this.uploadLoading) {
      return;
    }
    try {
      this.uploadLoading = true;
      const res: any = await this.services.uploadFileData(file);
      this.uploadLoading = false;

      if (res.code == 0) {
        this.message.success('图片上传成功');
        this.validateForm.get('url')?.setValue(res.data);
      } else {
        this.message.error(res.message || '图片上传失败');
      }
    } catch (error: any) {
      this.uploadLoading = false;
      this.validateForm.get('url')?.setValue('');
      this.message.error(error || '图片上传失败');
    }
  }
}
